package com.gufe.controller.user.mp;


import com.gufe.dto.FeedbackDTO.FeedbackDTO;
import com.gufe.result.Result;
import com.gufe.service.user.mp.FeedbackService;
import com.gufe.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/api/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;

    @Value("${zbt.jwt.user-secret-key}")
    private String jwtSecret;

    @PostMapping("/submit")
    public Result<String> submitFeedback(@RequestBody FeedbackDTO feedbackDTO,
                                             @RequestHeader(HttpHeaders.AUTHORIZATION) String authorizationHeader) {
        String userId = extractUserIdFromToken(authorizationHeader);

        if (userId == null || userId.isEmpty()) {
            return Result.error("无法获取用户信息，请检查登录状态");
        }

        boolean success = feedbackService.submitFeedback(feedbackDTO, userId);
        if (success) {
            return Result.success("意见反馈提交成功");
        } else {
            return Result.error("意见反馈提交失败");
        }
    }

    private String extractUserIdFromToken(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            try {
                Claims claims = JwtUtil.parseJWT(jwtSecret, token);
                Object userIdObject = claims.get("userId"); // 获取到的可能是 Integer 或 String

                if (userIdObject instanceof Integer) {
                    return String.valueOf(userIdObject); // 如果是 Integer，转换为 String
                } else if (userIdObject instanceof String) {
                    return (String) userIdObject;      // 如果是 String，直接返回
                } else {
                    // 处理其他意外类型，例如返回 null 或抛出异常
                    System.err.println("userId Claim 类型不正确: " + (userIdObject != null ? userIdObject.getClass().getName() : "null"));
                    return null;
                }
            } catch (Exception e) {
                System.err.println("Token解析失败: " + e.getMessage());
                return null;
            }
        }
        return null;
    }
}
